
//
//  AllCourseViewController.swift
//  ddx0513
//
//  Created by jiang yongbin on 15/6/7.
//  Copyright (c) 2015年 jiang yongbin. All rights reserved.
//

import Foundation
import UIKit

class AllCourseViewController: UITableViewController {
    
   // var listVideos : NSMutableArray!
    
    var dataArr:NSMutableArray = []
    var imageArr:NSMutableArray = []
    var hitArr:NSMutableArray = []
    var lessonidArr:NSMutableArray = []
    var courseArr = NSArray()
    var itemList:AllCourseItem! = nil
    var totalCount = 0
    var thiscount = 0
    var thispn = 1
    var sectionId:NSMutableArray = []
    var isFree:NSMutableArray = []
     var lineImageView:UIImageView! = nil
    var allcourse:AllCourseViewController! = nil
    var learningcourse:LearningViewController! = nil
    var scoreArr:NSMutableArray = []
    var thisPage = 0
    var searchTime: Int64?
    var pageSize = 18
    var pageNum = 1
    var totalPage = 0
    

    var datas:Int = 4
    func datainit()
    {
        thisPage = 0
        dataArr.removeAllObjects()
        lessonidArr.removeAllObjects()
        imageArr.removeAllObjects()
        hitArr.removeAllObjects()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        rootController.navigationController?.setNavigationBarHidden(true, animated: true)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("weixinPayHandler:"), name: StringUtils.WeipayNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("aliPayHandler:"), name: StringUtils.AlipayNotification, object: nil)
        
        self.tableView.tableFooterView = UIView(frame: CGRectZero)
        //下拉刷新
        self.tableView.header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in
            self.datainit()
            self.getData(1)
        })
        self.tableView.header.beginRefreshing()
        //datainit()
        //getData()
 
        
        
    }
    
    override func viewDidDisappear(animated: Bool) {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: StringUtils.WeipayNotification, object: nil)
        NSNotificationCenter.defaultCenter().removeObserver(self, name: StringUtils.AlipayNotification, object: nil)
    }
    
    func weixinPayHandler(notification: NSNotification) {
        let resp = notification.object as! BaseResp
        
        switch(resp.errCode) {
        case 0:
            ViewUtils.popMessage(self, title: "微信支付结果", message: "订单支付成功")
        case -2:
            ViewUtils.popMessage(self, title: "微信支付结果", message: "用户点击取消并返回")
        default:
            ViewUtils.popMessage(self, title: "微信支付结果", message: "订单支付失败")
            
        }
    }
    
    func aliPayHandler(notification: NSNotification) {
        let resultStatus = notification.object as! String
        
        ViewUtils.popMessage(self, title: "支付宝支付结果", message: "StringUtils.alipayErrorCode[resultStatus]!")
    }

        // Do any additional setup after loading the view.

    func getData(pageNum: Int)
    {
        var userid:Int = DBUtils.mem.userId
        var token:String = DBUtils.mem.token
        var sort:Int = 100
        var a: [String: AnyObject]?
        if(DBUtils.mem.sortItem == 0)//最新
        {
            sort = 1
            
        }
        else if(DBUtils.mem.sortItem == 1)//热门
        {
            sort = 2
        }
        else if(DBUtils.mem.sortItem == 2)//评价
        {
            sort = 3
        }
        else//默认
        {
             sort = 0
        }
        
        //筛选
        if (DBUtils.mem.sortItem == 3)
        {
            sort = 0
            var grade = ""
            var topic = ""
            var edition = ""
          
            for key1 in GlobalData.grade.allKeys
            {
                let str:NSString =   GlobalData.grade.objectForKey(key1) as! NSString
                let keystring:String = key1 as! String
                if(str == "1")
                {
                    if(grade.isEmpty)
                    {
                         grade += keystring
                    }
                    else
                    {
                         grade += ","
                         grade += keystring
                    }
                }
            }
            
            for key2 in GlobalData.topic.allKeys
            {
                let str:NSString =   GlobalData.topic.objectForKey(key2) as! NSString
                let keystring:String = key2 as! String
                if(str == "1")
                {
                    if(topic.isEmpty)
                    {
                        topic += keystring
                    }
                    else
                    {
                        topic += ","
                        topic += keystring
                    }
                }
            }
            
            for key3 in GlobalData.edition.allKeys
            {
                let str:NSString =   GlobalData.edition.objectForKey(key3) as! NSString
                let keystring:String = key3 as! String
                if(str == "1")
                {
                    if(edition.isEmpty)
                    {
                        edition += keystring
                    }
                    else
                    {
                        edition += ","
                        edition += keystring
                    }
                }
            }
             a = ["grade":grade,"topic":topic,"edition":edition,"sort":sort,"pn":pageNum,"ps":pageSize]
            if (pageNum > 1) {
                a?.updateValue(NSNumber(longLong: self.searchTime!), forKey: "searchtime")
            }
             NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLLessonList() , parameters: a, responseHandler: nil, netErrorHandler: nil, successHandler: firstTableview, interErrorHandler: nil, jsonErrorHandler: nil)
            
            DBUtils.mem.sortItem = 0
        }
        else
        {
            a = ["sort":sort,"pn":pageNum,"ps":pageSize]
            if (pageNum > 1) {
                a?.updateValue(NSNumber(longLong: self.searchTime!), forKey: "searchtime")
            }
            NetUtils.netRequest(Method.GET, URLString: NetUtils.getURLLessonList() , parameters: a, responseHandler: nil, netErrorHandler: nil, successHandler: firstTableview, interErrorHandler: nil, jsonErrorHandler: nil)
            
        }

        //DBUtils.mem.thisPage = thispn + 1
 
    }
    //MARK: - 网络回调函数
    func firstTableview (json: JSON) {
        totalCount = json["totalcount"].int!
        let thiscount = json["list"].count
        for (var i = 0;i < thiscount; i++ )
        {
            dataArr.addObject(json["list"][i]["lessonname"].string!)
            imageArr.addObject(json["list"][i]["imgurl"].string!)
            hitArr.addObject(json["list"][i]["hit"].int!)
            lessonidArr.addObject(json["list"][i]["lessonid"].int!)
            scoreArr.addObject(json["list"][i]["score"].int!)
        }
        thisPage++
        self.tableView.reloadData()
        if (self.thisPage == 1) {
            self.tableView.header.endRefreshing()
            self.searchTime = json["searchtime"].int64!
            self.totalPage = Int(ceil(Double(totalCount) / Double(pageSize)))
            
            self.tableView.footer = MJRefreshAutoNormalFooter(refreshingBlock: { () -> Void in
                self.getData(self.thisPage+1)
            })
            
            if (self.totalPage == self.thisPage) {
                self.tableView.footer.noticeNoMoreData()
            }
        }
        
        if (self.totalPage > self.thisPage) {
            self.tableView.footer.endRefreshing()
        } else {
            self.tableView.footer.noticeNoMoreData()
        }
     
        //self.tableView.reloadData()
        
    }
    func sort()
    {
       
    }
    
    func insertNewObject(sender: AnyObject) {
           }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    // MARK: - Table view data source
    //返回节的个数
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }
    //返回某个节中的行数
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete method implementation.
        // Return the number of rows in the section.
        //return dataArr.count
        return dataArr.count
    }
    //为表视图单元格提供数据，该方法是必须实现的方法
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       
        
        
        ///////////////////

        var tableCell :AllCourseItem = tableView.dequeueReusableCellWithIdentifier("AllCourseItem2") as! AllCourseItem
       
        if (dataArr.count == 0)
        {
            return tableCell
        }
        
        
        var s = dataArr.objectAtIndex(indexPath.row) as? String
        tableCell.courseName.text = s
        var starKind = scoreArr.objectAtIndex(indexPath.row) as! Int
        if (starKind == 1){
           tableCell.starImage.image = UIImage(named: "一星.png")
        }
        else if (starKind == 2)
        {
            tableCell.starImage.image = UIImage(named: "二星.png")
        }
        else if (starKind == 3)
        {
            tableCell.starImage.image = UIImage(named: "三星.png")
        }
        else if (starKind == 4)
        {
            tableCell.starImage.image = UIImage(named: "四星.png")
        }
        else if (starKind == 5)
        {
            tableCell.starImage.image = UIImage(named: "星级.png")
        }
        else
        {
            //需要5颗灰色的
            tableCell.starImage.image = UIImage(named: "灰星.png")
        }
        
        var str = hitArr.objectAtIndex(indexPath.row) as! Int
        tableCell.numOfPeople.text =  "\(String(str))人在学"
        tableCell.accessoryType = UITableViewCellAccessoryType.None
        var url:String = imageArr.objectAtIndex(indexPath.row) as! String
      //  tableCell.imageView.image = nil
        
        //let url1 = NSURL(string : (url))
        //var data = NSData(contentsOfURL: url1!, options: NSDataReadingOptions(), error: nil)
       // tableCell.courseImage.image = UIImage(data:data!)
        /////////
        DBUtils.getImageFromFile(url, successHandler: { (imgUrl, img) -> Void in
            if (url == imgUrl) {
                tableCell.courseImage.image = img
            }
        })

        /////////////
        
       // var lineImageView = UIImageView(frame: CGRectMake(0, 58, 320, 2))
       // self.lineImageView(CGRectMake(0, 50, UIScreen.mainScreen().bounds.size.width, 2)
            
        //    lineImageView.image = UIImage(named:"线.png")
            
        //    tableCell.contentView.addSubview(lineImageView)
        
       

        /////////////
        return tableCell
        
    }


    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        var allcoursedetail = UIStoryboard(name: "AllCourse", bundle: nil).instantiateViewControllerWithIdentifier("AllCourseDetail") as! AllCourseDetail
        //containerDetail.CurrentContainer=item
        rootController.navigationController?.pushViewController(allcoursedetail, animated: true)
//        self.presentViewController(allcoursedetail, animated: true, completion: nil)
        var lessonid = lessonidArr.objectAtIndex(indexPath.row) as! Int

        allcoursedetail.lessonId = lessonid
        
        var lessonName = dataArr.objectAtIndex(indexPath.row) as? String
        allcoursedetail.lessonName = lessonName!
        
        
        
       // var storyBoard = UIStoryboard(name: "Learning", bundle: nil)
      //  var learningcourse = storyBoard.instantiateViewControllerWithIdentifier("Learning") as! LearningViewController
       // learningcourse.lessonId = lessonid
        
       // println(learningcourse.lessonId)
        
      
        
    }
    
    
   /*
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        var theSegue = segue.destinationViewController as! AllCourseDetail
        theSegue.lessonId = 10
    }
    */
    
    
    
    // 支持单元格编辑功能
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    
    }
    
    
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
            }
    
    
    
    // Override to support conditional rearranging of the table view.
    //在编辑状态，可以拖动设置item位置
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    
    /*override func  viewWillAppear(animated: Bool) {
       // super.viewWillAppear(<#animated: Bool#>)
        
        super.tableView.deselectRowAtIndexPath(self.tableView.indexPathForSelectedRow()!, animated: true)
    }*/
    override func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
     //   var lineImageView = UIImageView(frame: CGRectMake(0, 58, 320, 2))
        //var footer = UIView(frame: CGRectMake(0, 0,
          //  UIScreen.mainScreen().bounds.size.width, 5))
        //self.tableView.tableFooterView?.frame = CGRectZero
        var footer = UIView(frame: CGRectZero)
        
        footer.backgroundColor = UIColor.clearColor()
        return footer;
    }
    
    /*override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 75
    }*/
    override func  layoutSublayersOfLayer(layer: CALayer!) {
    
        
    }
    
    
    override func scrollViewDidScroll(scrollView: UIScrollView) {

           }
    // MARK: - Navigation
    
    //给新进入的界面进行传值
    
    
   /* override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
        var allCourseDetail = segue.destinationViewController as! AllCourseDetail
       // allCourseDetail.lessonId =
        var index = tableView.indexPathForSelectedRow()
        var lessonid = lessonidArr.objectAtIndex(index!.row) as! Int

        allCourseDetail.lessonId = lessonid
        println(allCourseDetail.lessonId)
        // segue.destinationViewController.lessonId = lessonid
        
    }*/


    
    
}